package org.huzhp.console.entity.vo;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;
import org.apache.commons.lang.StringUtils;
import org.huzhp.console.entity.GatewayFilter;
import org.springframework.beans.BeanUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description: GatewayFilterVo
 * @Author: huzp
 * @CreateDate: 2020/3/12 15:38
 * @Version: 1.0
 */
@Data
public class GatewayFilterVo {

    private String filterName;

    private String filterArgs;

    private Map filterArgsMap;

    public GatewayFilter build() {
        if (this == null) {
            return null;
        }
        GatewayFilter filter = new GatewayFilter();
        BeanUtils.copyProperties(this, filter);
        return filter;
    }

    public Object buildGatewayJson() {
        Map<String, Object> jsonMap = new HashMap<>(2);
        jsonMap.put("name", this.filterName);
        jsonMap.put("args", getArgs());
        return jsonMap;
    }

    public Map getArgs() {
        if (this.filterArgsMap != null) {
            return this.filterArgsMap;
        }
        try {
            if (StringUtils.isNotEmpty(this.filterArgs)) {
                ObjectMapper mapper = new ObjectMapper();
                return mapper.readValue(this.filterArgs, Map.class);
            }
        } catch (JsonProcessingException e) {

        }
        return null;
    }
}
